package sk.atletis.atletika;

import java.io.ByteArrayOutputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;

public class DataReceiver extends BroadcastReceiver 
{
	public static final String ALARM_BROADCAST = "alarmBroadcast";
	public static final String NEW_ARTICLES = "newArticles";
	
	@Override
	public void onReceive(Context ctx, Intent intent) 
	{
		updateData(ctx);
	}
	
	// Updates data in database
	private void updateData(final Context ctx)
	{
		(new Thread(new Runnable() 
		{
			public void run() 
			{
				try 
				{
					updateArticles(ctx);
					updateCompetitions(ctx);
					updateImages(ctx);
				} 
				catch (Exception e) 
				{
					e.printStackTrace();
				}
			}
		})).start();
	}
	
	// Gets data from database to List
    private int getMaxArticleId(Context ctx) 
    {
		try
		{
			Cursor c = ctx.getContentResolver().query(
				ArticlesContract.CONTENT_URI_ARTICLES, 
				ArticlesContract.PROJECTION, 
				null,
				null,
				ArticlesContract.SORT_DEFAULT + " LIMIT 1");

			if (c != null)
			{
				c.moveToFirst();
				
				if (!c.isAfterLast())
				{
					return c.getInt(c.getColumnIndex(ArticlesContract._ID));
				}
			}
		}
		catch (Exception e) {
			
		}
		
		return 0;
	}
	
	private void updateArticles(final Context ctx)
	{
		int maxId = getMaxArticleId(ctx);
		JsonHandler handler = new JsonHandler(ctx, "http://atletikasvk.sk/DataOutput/Articles?count=20&max=" + String.valueOf(maxId));
		handler.updateArticles();
	}
	
	private void updateCompetitions(final Context ctx)
	{
		JsonHandler handler = new JsonHandler(ctx, "http://atletikasvk.sk/DataOutput/Competitions?count=20");
		handler.updateCompetitions();
	}
	
	private void updateImages(final Context ctx)
	{
		try 
		{
			// Gets Articles without image
			Cursor c = ctx.getContentResolver().query(
					ArticlesContract.CONTENT_URI_ARTICLES, 
					ArticlesContract.PROJECTION_IMAGE, 
					ArticlesContract.IMAGEPATH + " IS NOT NULL AND " + ArticlesContract.IMAGEFILE + " IS NULL",
					null, 
					ArticlesContract.SORT_DATE_DESC);
			
			// Move to first
			c.moveToFirst();
			
		    while (!c.isAfterLast()) 
		    {
		    	// Image URL
		    	long articleId = c.getLong(c.getColumnIndex(ArticlesContract._ID));
		    	String imageUrl = "http://atletikasvk.sk/Content/articles/" + c.getString(c.getColumnIndex(ArticlesContract.IMAGEPATH));
				
		    	// Get Image
		    	DefaultHttpClient httpClient = new DefaultHttpClient();
				HttpGet get = new HttpGet(imageUrl);
				HttpResponse httpResponse = httpClient.execute(get);
				HttpEntity httpEntity = httpResponse.getEntity();
				byte[] arrImage = EntityUtils.toByteArray(httpEntity);
				
				// Convert Image to JPEG
				Bitmap bmp = BitmapFactory.decodeByteArray(arrImage, 0, arrImage.length);
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				bmp.compress(Bitmap.CompressFormat.JPEG, 50, stream);
				
				// ContentValues
				ContentValues values = new ContentValues();
				values.put(ArticlesContract._ID, articleId);
				values.put(ArticlesContract.IMAGEFILE, stream.toByteArray());
				
				// Update
				ctx.getContentResolver().update(Uri.withAppendedPath(ArticlesContract.CONTENT_URI_ARTICLES, String.valueOf(articleId)), 
						values, null, null);
				
				c.moveToNext();
		    }
		    
		    // Close the cursor
		    c.close();
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
	
	
	
}
